package com.wrt.produce.service.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Base64;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.druid.pool.DruidDataSource;
import com.wrt.produce.service.DataSourceChangeService;
import com.wrt.produce.source.DynamicDataSource;

import lombok.extern.log4j.Log4j2;

@Service
@Log4j2
public class DataSourceChangeServiceImpl implements DataSourceChangeService {

	@Value("${spring.datasource.driver-class-name}")
	private String driverclass;
	
	@Resource
	DynamicDataSource dataSource;

	@Override
	public boolean testConnect(String url, String name, String password) {
		Connection connection = null;
		try {
			Class.forName(driverclass);
			connection = DriverManager.getConnection(url, name, new String(Base64.getDecoder().decode(password)));
			String dataurl = connection.getMetaData().getURL();
			return StringUtils.isNotBlank(dataurl);
		} catch (ClassNotFoundException | SQLException e) {
			log.error(e.getMessage(), e);
			return false;
		} finally {
			if (null != connection) {
				try {
					connection.close();
				} catch (SQLException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	@Override
	public void changeDataSorce(String url, String name, String password, String key) {
		DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(name);
        druidDataSource.setPassword(new String(Base64.getDecoder().decode(password)));
        dataSource.addDataSource(key, druidDataSource);
	}
}
